package io.github.yotta.logger.core.support;

import io.github.yotta.logger.anno.annotation.context.BizIdLogContext;
import io.github.yotta.logger.anno.annotation.provider.BizIdFrom;
import io.github.yotta.logger.core.model.LogAnnoMetaData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;

/**
 * @author yotta
 * @date 2025/3/13 11:38
 */
@Slf4j
public class BizIdProviderDiscover {

    public Object getBizIdBefore(LogAnnoMetaData logAnnoMetaData, Object[] arguments, Method targetMethod) {
        return parseFromBizPath(logAnnoMetaData, arguments, null, targetMethod);
    }

    public Object getBizIdAfter(LogAnnoMetaData logAnnoMetaData, Object[] arguments, Object result, Method targetMethod) {
        Object bizIdFromContext = getBizIdFromContext();
        if (null != bizIdFromContext) {
            return bizIdFromContext;
        }
        return parseFromBizPath(logAnnoMetaData, arguments, result, targetMethod);
    }

    private Object getBizIdFromContext() {
        return BizIdLogContext.get();
    }


    private Object parseFromBizPath(LogAnnoMetaData logAnnoMetaData, Object[] arguments, Object result, Method targetMethod) {
        try {
            String bizIdPath = logAnnoMetaData.getBizIdPath();
            if (StringUtils.isEmpty(bizIdPath)) {
                return null;
            }
            if (BizIdFrom.PARAM.equals(logAnnoMetaData.getBizIdFrom())) {
                return ParamResolver.resolve(targetMethod, bizIdPath, arguments);
            } else {
                return ParamResolver.resolve(bizIdPath, result);
            }
        } catch (Exception e) {
            log.error("parse bizId from path error; path is [{}] from [{}] ", logAnnoMetaData.getBizIdPath(), logAnnoMetaData.getBizIdFrom(), e);

        }
        return null;
    }


}
